# -*- coding: utf-8 -*-
import logging
import json

from django.views.decorators.http import require_POST
from django.http import HttpResponse

from api.transaction import handler
from common.third.pay import unionagency
from common.withdraw import unionagency_withdraw
from common.utils import exceptions as err
from common.utils.decorator import response_wrapper
from common.utils.api import (check_params)
from common.utils.decorator import response_wrapper
from common.withdraw import unionagency_withdraw
from common.withdraw.unionagency_withdraw import generate_sign, API_KEY
from common.utils.exceptions import ParamError, AuthenticateError

_LOGGER = logging.getLogger('pay')


@require_POST
def charge_callback(request):
    try:
        unionagency.check_notify_sign(request)
        # we must return 'success' after processing
        return HttpResponse('success', status=200)
    except err.ParamError as e:
        _LOGGER.warn('unionagency notify param error, %s', e)
        return HttpResponse('success', status=200)
    except Exception as e:
        _LOGGER.exception('unionagency notify exception.(%s)' % e)
        return HttpResponse('failure', status=500)


@require_POST
def withdraw_charge_callback(request):
    try:
        unionagency_withdraw.check_notify_sign(request)
        return HttpResponse('success', status=200)
    except Exception as e:
        _LOGGER.exception('unionagency notify exception.(%s)' % e)
        return HttpResponse('failure', status=500)


@require_POST
@response_wrapper
def submit_from_third(request):
    param_dct = json.loads(request.body)
    check_params(param_dct, ['user_id', 'pay_amount', 'type', 'sign'])
    sign = param_dct.pop('sign')
    if sign != generate_sign(param_dct, API_KEY):
        raise err.AuthenticateError(u'签名不合法')
    pay_amount = float(param_dct['pay_amount'])  # 充值金额
    user_id = int(param_dct['user_id'])
    type = param_dct['type']
    return handler.submit_unionagency_from_third(user_id, pay_amount, type)
